package controllers

import (
	"bytes"
	"github.com/astaxie/beego"
	"github.com/gorilla/websocket"
	"net/http"
	"fmt"
	."LiquidMeasurement/forms"
	."LiquidMeasurement/respone_forms"
	"encoding/json"
)


const (
	DEVICE_GATE_JOIN = iota
	DEVICE_JOIN
	DEVICE_HEART
	DEVICE_LEAVE
	DEVICE_WARN
	DEVICE_INQUERY
	DEVICE_FAIL
	HEART_GATE_JOIN

//	DEVICE_JOIN = iota

)


const (
	SUCESS = 200
	NOT_FOUND = 201
	FOUND = 202

//	DEVICE_JOIN = iota

)

type DeviceConnController struct {
	beego.Controller
}


func (this *DeviceConnController) Join() {

}

func (this *DeviceConnController) Leave() {

}


func (this *DeviceConnController) DeviceJoin()  {
	//mac := this.GetString("mac")     //获取连接中的mac

	// Upgrade from http request to WebSocket.
	ws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 2048, 2048)
	//fmt.Printf("err",err)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(this.Ctx.ResponseWriter, "Not a websocket handshake", 400)
		//如果错误，随便返回一些数据，以防框架报错
		respone_json := SiteResponeType{SITE_SUCCESS, INVALIDS, INVALIDS}
		this.Data["json"] = &respone_json
		this.ServeJSON();
		return
	} else if err != nil {
		beego.Error("Cannot setup WebSocket connection:", err)
//		//如果错误，随便返回一些数据，以防框架报错
		respone_json := SiteResponeType{SITE_SUCCESS, INVALIDS, INVALIDS}
		this.Data["json"] = &respone_json
		this.ServeJSON();
		return
	}
	var data DeviceConnForm
	//ws.SetReadDeadline()
	// Message receive loop.
	for {

		_, p, err := ws.ReadMessage()
		if err != nil {

			//如果错误，随便返回一些数据，以防框架报错
			beego.Error("websocket read err:", err)
			//Leave(string(mac))
			respone_json := CommonRespone{}

			 this.Data["json"] = &respone_json
			this.ServeJSON();
			return
		}

		fmt.Println("recive data",string(p))
		err_Unmarshal := json.Unmarshal(p,&data)
		if err_Unmarshal != nil{
			//如果错误，随便返回一些数据，以防框架报错
			beego.Error("json Unmarshal err:", err)
			fmt.Println("json data",string(p))
			ws.Close()
			respone_json := DeviceResponType{Optype:201}
			this.Data["json"] = &respone_json
			this.ServeJSON();
			return
		}else {
			if(data.Optype == DEVICE_JOIN){
				//a,_ := data.(DeviceInfo)
				JoinDevice(ws, string(data.Mac),data)      //设备加入到连接池中
				data.ResponeCode = 200
				//				fmt.Println("DEVICE_JOIN:",data)
//				defer LeaveDevice(string(data.Mac))
				//data.ResponeCode = 200
				json_str,_ := json.Marshal(data)
				wend_str := bytes.Join([][]byte{json_str,[]byte("\r\n")},[]byte(""))
				fmt.Printf("device join respone:%s",string(wend_str))
				//json_str.
				if err := ws.WriteMessage(websocket.TextMessage,wend_str ); err != nil {
					//return false
					beego.Error("send respone msg err:", err)
				}
			}else if(data.Optype == DEVICE_HEART){
				if _,ok := isDevicesExist(data.DeviceID);ok == true {
					data.ResponeCode =  200
				}else{
					data.ResponeCode = 204

				}
				DeviceHeart(data)
				json_str,_ := json.Marshal(data)
				//json_str := []byte("tests\r\n")
				wend_str := bytes.Join([][]byte{json_str,[]byte("\r\n")},[]byte(""))
				fmt.Printf("heart respone:%s",string(wend_str))
				if err := ws.WriteMessage(websocket.TextMessage,wend_str ); err != nil {
					//return false
					beego.Error("send respone msg err:", err)
				}
			}else if(data.Optype == DEVICE_LEAVE){

				LeaveDevice(data)

			}else if(data.Optype == DEVICE_WARN){
				json_str,_ := json.Marshal(data)
				//json_str := []byte("tests\r\n")
				wend_str := bytes.Join([][]byte{json_str,[]byte("\r\n")},[]byte(""))
				fmt.Printf("device warn rspoone :%s",string(wend_str))
				if err := ws.WriteMessage(websocket.TextMessage,wend_str ); err != nil {
					//return false
					beego.Error("send respone msg err:", err)
				}
			}else if(data.Optype == DEVICE_GATE_JOIN){
					JoinGateWay(ws,data.Mac)
					//defer LeaveGateway(data.Mac)
					data.ResponeCode = 200
					json_str,_ := json.Marshal(data)
					wend_str := bytes.Join([][]byte{json_str,[]byte("\r\n")},[]byte(""))
					fmt.Printf("gateway join respone:%s",string(wend_str))
					//json_str.
					if err := ws.WriteMessage(websocket.TextMessage,wend_str ); err != nil {
						//return false
						beego.Error("send respone msg err:", err)
					}
			}else if(data.Optype == HEART_GATE_JOIN){
				//JoinGateWay(ws,data.Mac)
				//defer LeaveGateway(data.Mac)
				data.ResponeCode = 200
				json_str,_ := json.Marshal(data)
				wend_str := bytes.Join([][]byte{json_str,[]byte("\r\n")},[]byte(""))
				fmt.Printf("gateway heart respone:%s",string(wend_str))
				//json_str.
				if err := ws.WriteMessage(websocket.TextMessage,wend_str ); err != nil {
					//return false
					beego.Error("send respone msg err:", err)
				}
			}else if(data.Optype == DEVICE_INQUERY){
				//如果有查找到deviceid对应的设备,将设备的BindID赋值给data,返回给设备,否则返回0
				if device,ok := isDevicesExist(data.DeviceID);ok == true{
					data.BindID = device.BindID
					data.ResponeCode = 200
				}else{
					data.BindID = 0
				}

				json_str,_ := json.Marshal(data)
				wend_str := bytes.Join([][]byte{json_str,[]byte("\r\n")},[]byte(""))
				fmt.Printf("device inquery respone:%s",string(wend_str))
				//json_str.
				if err := ws.WriteMessage(websocket.TextMessage,wend_str ); err != nil {
					//return false
					beego.Error("send respone msg err:", err)
				}
			}



			// := DeviceResponType{Optype:201}

		}

		//publish <- newEvent(models.EVENT_MESSAGE, uname, string(p))
	}
	//Leave(string(mac))
	//如果错误，随便返回一些数据，以防框架报错

}


